<template>
  <div>
    <!-- 主表单区域 -->
    <a-form-model ref="form" :model="formData" :rules="rules">
      <a-divider orientation="left"> 基本信息 </a-divider>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="SKU编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skuCode">
            <a-input-search
              v-model="formData.skuCode"
              placeholder="请输入sku编码"
              :disabled="!isAdd"
              @change="skuChange"
              @search="createSku"
              :maxLength="20"
            >
              <a-button slot="enterButton" :disabled="!isAdd">生成</a-button>
            </a-input-search>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nameCn">
            <a-input v-model="formData.nameCn" placeholder="请输入产品名称" :maxLength="255"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品英文名 " :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nameEn">
            <a-input v-model="formData.nameEn" placeholder="请输入产品英文名" :maxLength="255"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="组合状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="constituteStatus">
            <j-search-select-tag-new
              v-model="formData.constituteStatus"
              dictCode="archive_constitute_status"
              placeholder="请选择组合状态"
              @change="constituteStatusChange"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="成本中心" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deptCode">
            <j-url-select
              placeholder="请选择产品所属成本中心"
              v-model="formData.deptCode"
              :disabled="disabledDept"
              :allowClear="false"
              url="/sys/costCenter/queryAllByUserId"
            />
            <a-tooltip placement="top" :overlayStyle="{ 'min-Width': '300px' }">
              <template slot="title">
                <div>1、被使用的产品不能更换成本中心</div>
                <div>2、组合产品中存在子产品时不允许更换</div>
              </template>
              <a-icon type="info-circle" class="dept-hint-icon" />
            </a-tooltip>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="销售状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sellStatus">
            <j-search-select-tag-new
              v-model="formData.sellStatus"
              dictCode="archive_sell_status"
              placeholder="请选择销售状态"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8" v-show="formData.sellStatus == '4'">
          <a-form-model-item label="停售原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="haltStatus">
            <j-search-select-tag-new
              v-model="formData.haltStatus"
              :dictOptions="optionsHalt"
              placeholder="请选择停售原因"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
            <j-search-select-tag-new
              :multiple="true"
              v-model="formData.type"
              :dictOptions="optionsType"
              placeholder="请选择产品分类"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="category">
            <product-category-tree-select v-model="formData.category" placeholder="请选择产品类目" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="开发负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="developer">
            <j-url-select
              v-model="formData.developer"
              placeholder="请选择"
              optionLabel="username"
              url="/sys/user/getAllUserByOrg"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="设计负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="designer">
            <j-url-select
              v-model="formData.designer"
              placeholder="请选择"
              optionLabel="username"
              url="/sys/user/getAllUserByOrg"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="销售负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="saleHead">
            <j-url-select
              v-model="formData.saleHead"
              placeholder="请选择"
              optionLabel="username"
              url="/sys/user/getAllUserByOrg"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="销售人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesperson">
            <j-url-select
              v-model="formData.salesperson"
              :multiple="true"
              placeholder="请选择销售人员，可多选"
              optionLabel="username"
              url="/sys/user/getAllUserByOrg"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="EAN码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="eanCode">
            <a-input v-model="formData.eanCode" placeholder="请输入EAN码" :maxLength="50"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="UPC码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="upcCode">
            <a-input v-model="formData.upcCode" placeholder="请输入UPC码" :maxLength="50"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品使用日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userDateTime">
            <j-date
              placeholder="请选择产品使用日期"
              v-model="formData.userDateTime"
              :show-time="true"
              date-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="商品描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depict">
            <a-textarea v-model="formData.depict" rows="4" placeholder="请输入商品描述" :maxLength="128" />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item
            label="图片上传"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="hzArchiveInfoImgsList"
          >
            <j-upload-oss
              ref="imgsUpload"
              v-model="formData.hzArchiveInfoImgsList"
              fileType="image"
              :number="15"
              :showUploadList="showUploadList"
            />
            <a-alert type="warning" show-icon>
              <div slot="description">
                <div>1、支持上传单张照片大小不超过20M；至少上传1张照片且最多不超过15张。</div>
                <div>2、上传首张照片，默认为主图，拖动页面图片至第一个可修改为主图。</div>
              </div>
            </a-alert>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider orientation="left"> 产品规格 </a-divider>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="产品颜色" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="color">
            <a-input v-model="formData.color" placeholder="请输入产品颜色" :maxLength="50"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="size">
            <a-input v-model="formData.size" placeholder="请输入产品尺寸" :maxLength="50"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
            <a-input v-model="formData.brand" placeholder="请输入品牌" :maxLength="50"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品材质" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="material">
            <j-search-select-tag-new
              v-model="formData.material"
              :dictOptions="optionsMaterial"
              placeholder="请选择产品材质"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品等级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
            <j-search-select-tag-new
              v-model="formData.level"
              :dictOptions="optionsLevel"
              placeholder="请选择产品等级"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="侵权等级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="infringementLevel">
            <j-search-select-tag-new
              v-model="formData.infringementLevel"
              :dictOptions="optionsInfringementLevel"
              placeholder="请选择侵权等级"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider orientation="left"> 包装信息 </a-divider>
      <a-row>
        <a-col :span="8" class="pack-size-box">
          <a-form-model-item
            label="单品规格"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="lenWidtHeig"
          ></a-form-model-item>
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="len">
            <a-input-number
              class="input-number"
              v-model="formData.len"
              :min="0"
              :step="1"
              :precision="2"
              :max="999999.99"
              placeholder="长"
            />
          </a-form-model-item>
          <span class="hint">x</span>
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="widt">
            <a-input-number
              class="input-number"
              v-model="formData.widt"
              :min="0"
              :step="1"
              :precision="2"
              :max="999999.99"
              placeholder="宽"
            />
          </a-form-model-item>
          <span class="hint">x</span>
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="heig">
            <a-input-number
              class="input-number"
              v-model="formData.heig"
              :min="0"
              :step="1"
              :precision="2"
              :max="999999.99"
              placeholder="高"
            />
          </a-form-model-item>
          <span class="hint">cm</span>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品毛重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gw">
            <a-input-number
              style="width: 80%"
              v-model="formData.gw"
              :min="0"
              :step="1"
              :precision="4"
              :max="99999.9999"
              placeholder="请输入产品毛重"
            /><span class="input-number-unit">KG</span>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="产品净重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nw">
            <a-input-number
              style="width: 80%"
              v-model="formData.nw"
              :min="0"
              :step="1"
              :precision="4"
              placeholder="请输入产品净重"
              :max="99999.9999"
            /><span class="input-number-unit">KG</span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 现在没包装仓库数据，没法用暂时注释 -->
      <!-- <a-button type="primary" icon="plus" @click="addPack" style="margin-bottom: 10px">添加包装</a-button>
      <a-table
        :pagination="false"
        bordered
        :columns="packColumns"
        :data-source="formData.packTableData"
        :rowKey="(record, index) => index"
      >
        <template #warehouseSlot="text, record">
          <j-search-select-tag-new v-model="record.warehouseId" dict="hz_wms_warehouse_info" />
        </template>
        <template #warehouseMaterialSlot="text, record">
          <j-search-select-tag-new v-model="record.warehouseMaterialId" dictCode="wms_warehouse_provider" />
        </template>
        <span slot="action" slot-scope="text, record, index">
          <a @click="delPack(index)">删除</a>
        </span>
      </a-table> -->
    </a-form-model>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { getAction } from '@/api/manage'

import ProductCategoryTreeSelect from '@/components/business/ProductCategoryTreeSelect.vue'

export default {
  props: {
    // 是新增还是编辑
    isAdd: {
      type: Boolean,
      default: true,
    },
    // 要编辑的产品档案基本信息
    defaultData: {
      type: Object,
    },
  },
  components: {
    ProductCategoryTreeSelect,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      companyOrgCode: '', // 当前登录人所属的公司编码
      disabledDept: false, // 是否禁用成本中心选择
      formData: {
        skuCode: '', //sku编码
        nameCn: '', //产品名称
        nameEn: '', //产品名称英文
        constituteStatus: '1',
        deptCode: '', //成本中心
        sellStatus: '', //销售状态
        haltStatus: '', //停售原因
        type: '', //产品分类
        category: '', //产品类目
        developer: '', //开发负责人
        designer: '', //设计负责人
        saleHead: '', //销售负责人
        salesperson: '', //销售人员
        eanCode: '', //EAN码
        upcCode: '', //UPC码
        userDateTime: '', //产品使用日期
        depict: '', //商品描述
        hzArchiveInfoImgsList: '', //产品图片
        color: '', //产品颜色
        size: '', //产品尺寸
        brand: '', //品牌
        material: '', //产品材质
        level: '', //产品等级
        infringementLevel: '', //侵权等级
        len: '', //长
        widt: '', //宽
        heig: '', //高
        gw: '', //产品毛重
        nw: '', //产品净重
        lenWidtHeig: '别删，这个看似无用的字段是为了ui展示用', //别删，这个看似无用的字段是为了ui展示用
        //包装表格数据
        packTableData: [],
      },
      rules: {
        skuCode: [
          { required: true, message: '请输入sku编码!' },
          { pattern: /^[A-Za-z0-9_-]{5,20}$/, message: '仅支持5-20位大写字母、数字、下划线、中划线' },
        ],
        nameCn: [{ required: true, message: '请输入产品名称!' }],
        nameEn: [{ required: true, message: '请输入产品名称英文 !' }],
        constituteStatus: [{ required: true, message: '请输入组合状态!' }],
        deptCode: [{ required: true, message: '请选择成本中心!' }],
        sellStatus: [{ required: true, message: '请输入销售状态!' }],
        type: [{ required: true, message: '请输入产品分类!' }],
        hzArchiveInfoImgsList: [{ required: true, message: '请上传产品图!' }],
        color: [{ required: true, message: '请输入产品颜色!' }],
        size: [{ required: true, message: '请输入产品尺寸!' }],
        lenWidtHeig: [{ required: true, message: '这个只是为了显示必填效果ui!' }],
        len: [
          { required: true, message: '请输入长!' },
          { pattern: /^[+-]?(\d+)(\.\d{1,2})?$/, message: '请输入最多2位小数的数字' },
        ],
        widt: [
          { required: true, message: '请输入宽!' },
          { pattern: /^[+-]?(\d+)(\.\d{1,2})?$/, message: '请输入最多2位小数的数字' },
        ],
        heig: [
          { required: true, message: '请输入高!' },
          { pattern: /^[+-]?(\d+)(\.\d{1,2})?$/, message: '请输入最多2位小数的数字' },
        ],
        gw: [
          { required: true, message: '请输入产品毛重!' },
          { pattern: /^[+-]?(\d+)(\.\d{1,4})?$/, message: '请输入最多4位小数的数字' },
        ],
      },
      // 包装表格列
      packColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库',
          align: 'center',
          width: 200,
          dataIndex: 'warehouseId',
          scopedSlots: {
            customRender: 'warehouseSlot',
          },
        },
        {
          title: '包装材质',
          align: 'center',
          width: 200,
          dataIndex: 'warehouseMaterialId',
          scopedSlots: {
            customRender: 'warehouseMaterialSlot',
          },
        },
        {
          title: '包装规格(cm)',
          align: 'center',
          customRender(text, record) {
            if (record.warehouseId && record.warehouseMaterialId) {
              return `${record.len}x${record.widt}x${record.heig}`
            } else {
              return '请先选择仓库和材质'
            }
          },
        },
        {
          title: '重量(KG)',
          align: 'center',
          dataIndex: 'weight',
          customRender(text, record) {
            if (record.warehouseId && record.warehouseMaterialId) {
              return record.weight
            } else {
              return '请先选择仓库和材质'
            }
          },
        },
        {
          title: '操作',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        createSku: '/hzkj-product/product/archive/hzArchiveInfoBasic/createCode',
        queryCanEditDept: '/hzkj-product/product/archive/hzArchiveInfoBasic/changeCostById',
      },
      optionsHalt: [],
      optionsType: [],
      optionsMaterial: [],
      optionsLevel: [],
      optionsInfringementLevel: [],
    }
  },
  watch: {
    defaultData: {
      handler(val) {
        // 只要有值就赋值给formData
        if (val) {
          const newData = JSON.parse(JSON.stringify(val)) // 深拷贝，避免直接引用导致数据污染
          this.formData = {
            ...newData.base,
            hzArchiveInfoImgsList: newData.imgs.map((i) => i.url).join(','), //产品图片
            color: newData.other.color, //产品颜色
            size: newData.other.size, //产品尺寸
            brand: newData.other.brand, //品牌
            material: newData.other.material, //产品材质
            level: newData.other.level, //产品等级
            infringementLevel: newData.other.infringementLevel, //侵权等级
            len: newData.other.len, //长
            widt: newData.other.widt, //宽
            heig: newData.other.heig, //高
            gw: newData.other.gw, //产品毛重
            nw: newData.other.nw, //产品净重
            lenWidtHeig: '别删，这个看似无用的字段是为了ui展示用', //别删，这个看似无用的字段是为了ui展示用
            //包装表格数据
            packTableData: newData.packages,
            skuCode: newData.base.skuCode, // 如果公司编码已经获取完成，传来的skuCode包含编码，需要拆分
          }
          this.queryCanEditDept()
        }
      },
      immediate: true,
    },
  },
  computed: {
    showUploadList() {
      // 图片至少一张，用于控制删除按钮是否隐藏
      return { showRemoveIcon: this.formData.hzArchiveInfoImgsList.split(',').length > 1, showDownloadIcon: true }
    },
    userInfo() {
      return this.$store.getters.userInfo
    },
  },
  methods: {
    // 查询能否编辑成本中心
    queryCanEditDept() {
      // 被使用的产品
      // 单品是其他产品的子产品。
      // 组合产品已经添加了子产品。
      // 编辑时是以上三种情况不能更换成本中心；
      getAction(this.url.queryCanEditDept, {
        id: this.defaultData.base.id,
      }).then((res) => {
        if (res.success) {
          this.disabledDept = !!res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 加载下拉选项
    loadOptions() {
      ;['Halt', 'Type', 'Material', 'Level', 'InfringementLevel'].forEach((dict) => {
        getAction(`/hzkj-product/product/archive/archive${dict}Data/list`, {
          pageNo: 1,
          pageSize: 1000,
        }).then((res) => {
          if (res.success) {
            this[`options${dict}`] = res.result.records.map((item) => ({
              text: item.name,
              value: item.id,
            }))
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 接口生成sku
    createSku() {
      getAction(this.url.createSku).then((res) => {
        if (res.success) {
          this.formData.skuCode = this.companyOrgCode + res.result
          this.$refs.form && this.$refs.form.clearValidate('skuCode')
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 手动修改sku小写字母要转成大写字母
    skuChange() {
      this.formData.skuCode = this.formData.skuCode.toUpperCase()
    },
    // 添加包装
    addPack() {
      this.formData.packTableData.push({
        warehouseId: '',
        warehouseMaterialId: '',
      })
    },
    //删除包装
    delPack(index) {
      this.formData.packTableData.splice(index, 1)
    },
    // 组合状态变更时
    // 组合：显示子产品模块，隐藏采购信息模块、质检信息模块。
    // 单品：隐藏子产品模块，显示采购信息模块、质检信息模块。
    constituteStatusChange(val) {
      this.$emit('constituteStatusChange', val)
    },
    // 获取当前登录人所属的公司编码
    queryDirectlyDepartByOrgCode() {
      getAction('/sys/api/queryDirectlyDepartByOrgCode', { orgCode: this.userInfo.orgCode }).then((res) => {
        this.companyOrgCode = res.orgCode // 设置公司编码
        // 新增默认生成sku
        if (this.isAdd) {
          this.createSku()
        }
      })
    },
  },
  created() {
    this.loadOptions() // 加载下拉选项
    this.queryDirectlyDepartByOrgCode() // 获取当前登录人所属的公司编码
  },
  mounted() {
    //初始化图片拖动排序
    this.$nextTick(() => {
      new Sortable(this.$refs.imgsUpload.$el.querySelector('.ant-upload-list.ant-upload-list-picture-card'), {
        handle: '.ant-upload-list-picture-card-container',
        animation: 200,
        sort: true,
        onEnd: ({ newIndex, oldIndex }) => {
          //  oldIndex:谁
          //  newIndex:移动到哪儿
          const imgs = this.formData.hzArchiveInfoImgsList.split(',')
          if (imgs.length < 2) {
            //至少需要两张图片才有必要进行排序
            return
          }
          const currRow = imgs.splice(oldIndex, 1)[0]
          imgs.splice(newIndex, 0, currRow)
          // 下面这样操作主要是因为上传组件创建的图片预览elements是动态的，没法设置key，导致修改数组顺序样式无法正确渲染，就先清空，再重新赋值，会有闪动ui体验问题，暂时没找到好的解决方式，先这样处理
          this.formData.hzArchiveInfoImgsList = ''
          this.$nextTick(() => {
            this.formData.hzArchiveInfoImgsList = imgs.join(',')
          })
        },
      })
    })
  },
}
</script>

<style scoped lang="less">
.dept-hint-icon {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 30px;
}

.pack-size-box {
  display: flex;
  .input-number {
    width: 68px;
  }
  .hint {
    padding-top: 11px;
    font-size: 16px;
    margin: 0px 6px;
  }
}

.input-number-unit {
  display: inline-block;
  margin-left: -2px;
  width: 20%;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  background-color: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 0 4px 4px 0;
}
/deep/ .ant-upload-list-picture-card-container {
  cursor: move;

  &:first-child::before {
    content: '主图';
    position: absolute;
    left: 0;
    top: 0;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.65);
    z-index: 10;
    font-size: 12px;
    padding: 3px;
    border-radius: 5px 0 5px 0;
  }
}
</style>
